void gameFrame()
{
  checkInputs();
  lights();
  float m = millis();

  // Draw the screen mask at the start of each frame.
  background(0);


  //myShip.addForce(gField.field[(int)(myShip.position.x/gridRes)][(int)(myShip.position.y /gridRes)]);
  myShip.update();

  thePlanets.getViewport().moveTo(myShip.position.x, myShip.position.y);


  // handle each object
  Vector createdObjs = new Vector();
  float maxCurMass = 0;
  float minCurMass =  objMaxMass;
  int biggestObj = 0;
  int smallestObj = 0;

  for(int i = 0;i < vecObjs.size(); i++)
  {
    entityAbstractObject o = (entityAbstractObject) vecObjs.get(i);

    if(o.mass > maxCurMass)
    {
      maxCurMass = o.mass;
      biggestObj = i;
    }

    if(o.mass < minCurMass)
    {
      minCurMass = o.mass;
      smallestObj = i;
    }

    if(o.active == true)
    {
      gravitateObj(o);      
      o.update(fSpeed);

      for(int p = 0; p < numOfPlanets;p++)
      {
        if(checkCollisionObjPlanet(o, gField.planets[p]))
        {
          o.doCollision(createdObjs); 
          o.active = false;
        }
      }


      if( thePlanets.getViewport().isPointInBox(o.position.x, o.position.y) && o.active)
      {
        o.draw(-thePlanets.getViewport().tl.x , -thePlanets.getViewport().tl.y); 
      }
    }
    else
    {
      vecObjs.removeElementAt(i); 
    }

  }

  vecObjs.addAll(createdObjs);

  for(int i = 0; i < numOfPlanets;i++)
  {
    gField.planets[i].draw(-thePlanets.getViewport().tl.x , -thePlanets.getViewport().tl.y); 
  }

  myShip.draw(-thePlanets.getViewport().tl.x, -thePlanets.getViewport().tl.y );
  float m2 = millis() -m;
  print(m2);
  print(" objs: ");
  print(vecObjs.size());
  print(" b: ");
  print(maxCurMass);
  print(" : ");
  print(biggestObj);
  print(" s: ");
  print(minCurMass);
  print(" : ");
  println(smallestObj);
}


void gravitateObj(entityAbstractObject o)
{

  int x = (int)(o.position.x / gridRes);
  int y = (int)(o.position.y / gridRes);
  

  if(x >= gField.dataW)
  { 
    x = gField.dataW - 1;
  }
  else if(x < 0)
  {
    x = 0;
  }

  if(y >= gField.dataH)
  {
    y = gField.dataH - 1;
  }
  else if(y < 0)
  {
    y = 0;
  }
  o.addForce(gField.field[x][y]);
}

boolean checkCollisionObjPlanet(entityAbstractObject o, planet p)
{
  if( (o.position.x > p.bounds.tl.x ) && (o.position.x < p.bounds.br.x) )
  {
    if( (o.position.y > p.bounds.tl.y) && (o.position.y < p.bounds.br.y) ) 
    {
      float dx = p.position.x - o.position.x;
      float dy = p.position.y - o.position.y;
      
      
      float d = (float)Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));

      if(d < (o.rad + p.rad))
      {
        return true;
      }
    }
  }

  return false;
}

boolean checkCollisionObjObj(entityAbstractObject o, entityAbstractObject o2)
{
return true;
}
